<template>
  <div class="top-bar">
    <h1 class="title">后台管理系统</h1>
    <div class="user-section">
      <button class="icon-btn">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
          <line x1="3" y1="9" x2="21" y2="9"></line>
          <line x1="9" y1="21" x2="9" y2="9"></line>
        </svg>
      </button>
      <div class="user-info" @click="toggleDropdown">
        <el-avatar :src="userAvatar" :size="32" />
        <span class="username">{{ userName }}</span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="12"
          height="12"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          class="arrow"
          :class="{ 'dropdown-open': isDropdownOpen }"
        >
          <polyline points="6 9 12 15 18 9"></polyline>
        </svg>
      </div>
      <div class="dropdown" v-show="isDropdownOpen" @click.stop>
        <div class="dropdown-header">
          <el-avatar :src="userAvatar" :size="40" />
          <div class="user-details">
            <div class="user-name">{{ userName }}</div>
            <div class="user-role">{{ userRoleText }}</div>
          </div>
        </div>
        <div class="dropdown-divider"></div>
        <button @click="handleViewInfo">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
            <circle cx="12" cy="12" r="3"></circle>
          </svg>
          查看详细信息
        </button>
        <button @click="handleLogout">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
            <polyline points="16 17 21 12 16 7"></polyline>
            <line x1="21" y1="12" x2="9" y2="12"></line>
          </svg>
          退出登录
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入store
import { useUserStore } from '@/stores/user'
// 引入API
import { getUserInfo } from '@/api/auth'

const userStore = useUserStore()
const router = useRouter()
const isDropdownOpen = ref(false)

const userName = computed(() => {
  return userStore.name || '未知用户'
})

const userRoleText = computed(() => {
  return userStore.role === 'admin' ? '管理员' : userStore.role === 'user' ? '普通用户' : '未知角色'
})

const userAvatar = computed(() => {
  // 如果用户有头像，则使用用户头像，否则使用默认头像
  if (userStore.avatar) {
    // 处理不同角色的头像路径
    if (userStore.avatar.includes('icon-admin.png')) {
      return new URL('@/assets/imgs/login/icon-admin.png', import.meta.url).href
    } else if (userStore.avatar.includes('icon-user.png')) {
      return new URL('@/assets/imgs/login/icon-user.png', import.meta.url).href
    }
    return userStore.avatar
  }
  // 默认头像
  return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
})

// 获取用户详细信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      // 更新用户信息到store
      userStore.setUserInfo({
        ...userStore.$state,
        ...res.data
      })
    } else {
      console.warn('获取用户信息失败:', res.message || '未知错误')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const toggleDropdown = (event) => {
  event.stopPropagation()
  isDropdownOpen.value = !isDropdownOpen.value
}

const handleViewInfo = (event) => {
  event.stopPropagation()
  // 关闭下拉菜单
  isDropdownOpen.value = false
  // 跳转到用户信息页面
  router.push('/userinfo')
}

const handleLogout = (event) => {
  event.stopPropagation()
  // 关闭下拉菜单
  isDropdownOpen.value = false

  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 清除用户信息
      userStore.clearUserInfo()
      ElMessage.success('退出登录成功')
      // 跳转到登录页
      router.push('/login')
    })
    .catch(() => {
      // 取消退出
    })
}

// 点击其他地方关闭下拉菜单
const handleClickOutside = () => {
  isDropdownOpen.value = false
}

// 组件挂载时获取用户信息
onMounted(() => {
  // 如果store中没有用户信息，尝试从API获取
  if (!userStore.name) {
    fetchUserInfo()
  }

  // 添加全局点击事件监听器
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载前移除事件监听器
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2563eb;
  color: #fff;
  padding: 12px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;

  .title {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
  }

  .user-section {
    display: flex;
    align-items: center;
    gap: 16px;
    position: relative;

    .icon-btn {
      background: none;
      border: none;
      color: #fff;
      cursor: pointer;
      padding: 4px;
      border-radius: 4px;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }

      .username {
        font-size: 14px;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .arrow {
        transition: transform 0.2s;

        // 下拉菜单打开时箭头旋转
        &.dropdown-open {
          transform: rotate(180deg);
        }
      }
    }

    .dropdown {
      position: absolute;
      top: 50px;
      right: 0;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
      z-index: 1000;
      min-width: 240px;
      padding: 12px 0;

      .dropdown-header {
        display: flex;
        align-items: center;
        padding: 0 16px 12px;

        .user-details {
          margin-left: 12px;

          .user-name {
            font-weight: 500;
            color: #333;
            font-size: 16px;
          }

          .user-role {
            font-size: 12px;
            color: #999;
            margin-top: 4px;
          }
        }
      }

      .dropdown-divider {
        height: 1px;
        background-color: #eee;
        margin: 8px 0;
      }

      button {
        width: 100%;
        text-align: left;
        padding: 12px 16px;
        background: none;
        border: none;
        cursor: pointer;
        font-size: 14px;
        color: #333;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f3f4f6;
        }
      }
    }
  }
}
</style>
